package cn.sql_session;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.cj.jdbc.Driver;
import org.apache.ibatis.logging.nologging.NoLoggingImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.sql.SQLException;

public class SqlSessionThreadSecurityUtils {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory = null;
    private static String url = "jdbc:mysql://192.168.169.230:3306/mysteel_map?useUnicode=true&characterEncoding=UTF-8&useSSL=false&rewriteBatchedStatements=true&allowMultiQueries=true";

    private static String username = "adims_user";
    private static String password = "9PGzvMpQbWpR";

    // 构造函数私有
    private SqlSessionThreadSecurityUtils() {

    }

    // 读取配置文件
    static {
        DruidDataSource druidDataSource = new DruidDataSource();
        try {
            druidDataSource.setDriver(new Driver());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        Environment environment = new Environment("development", new JdbcTransactionFactory(), druidDataSource);
        Configuration configuration = new Configuration();
//        configuration.addMapper(WeatherToolMapper.class);
        configuration.setEnvironment(environment);
        configuration.setLogImpl(NoLoggingImpl.class);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

    }


    /**
     * 获取SqlSession
     *
     * @return
     */
    public static SqlSession getSqlSession() {

        SqlSession sqlSession = threadLocal.get();  // 从当前线程获取
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);  // 将sqlSession与当前线程绑定
        }
        return sqlSession;
    }

    /**
     * 关闭SqlSession
     */
    public static void close() {
        SqlSession sqlSession = threadLocal.get();  // 从当前线程获取
        if (sqlSession != null) {
            sqlSession.close();
            threadLocal.remove();
        }
    }
}